package com.dongdongshop.service.impl;

import com.dongdongshop.constant.RedisNewsConst;
import com.dongdongshop.mapper.TbSeckillGoodsMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillGoodsExample;
import com.dongdongshop.service.SeckillSericeI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class SeckillSericeImpl implements SeckillSericeI {

    @Resource
    private TbSeckillGoodsMapper seckillGoodsMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<TbSeckillGoods> findSeckillList() {
        //先查缓存，缓存没有，再查数据库 RedisNewsConst
        List<TbSeckillGoods> seckillList = redisTemplate.boundHashOps(RedisNewsConst.seckillList).values();
        if(null == seckillList || seckillList.size() <= 0){
            //条件查询
            TbSeckillGoodsExample example = new TbSeckillGoodsExample();
            TbSeckillGoodsExample.Criteria criteria = example.createCriteria();
            //查询审核通过的商品
            criteria.andStatusEqualTo("1");//0:未审核，1：审核成功，2：审核未成功
            criteria.andStartTimeLessThanOrEqualTo(new Date());//开始时间小于或等于当前时间
            criteria.andEndTimeGreaterThanOrEqualTo(new Date());//结束时间大于或等于当前时间
            criteria.andStockCountGreaterThan(0);//剩余库存大于0
            seckillList = seckillGoodsMapper.selectByExample(example);
            //遍历集合，将列表数据一个一个放到缓存中
            for (TbSeckillGoods goods : seckillList) {
                redisTemplate.boundHashOps(RedisNewsConst.seckillList).put(goods.getId(),goods);
                //将商品库存1存放到缓存
                redisTemplate.boundValueOps(goods.getId()).set(goods.getStockCount().toString());
            }
        }
        return seckillList;
    }

    @Override
    public TbSeckillGoods findSeckillGoods(long id) {

        TbSeckillGoods seckillList = (TbSeckillGoods)redisTemplate.boundHashOps(RedisNewsConst.seckillList).get(id);
        return seckillList;
    }
}
